import { Card, message, Form, Input, Table, Button, Modal } from "antd";
import "./index.scss";
import { getCategoryListApi, addCategoryApi } from "../../api";
import { useEffect, useState, useRef } from "react";

function Category() {
  const [categoryList, setcategoryList] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isUpdateCategory, setIsUpdateCategory] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const formRef = useRef();
  const onReset = () => {
    formRef.current.resetFields();
  };
  async function getCategoryList() {
    setIsLoading(true);
    const res = await getCategoryListApi().catch(() => {
      setIsLoading(false);
    });
    setIsLoading(false);
    const { status, data, msg } = res.data;
    if (status !== 0) return message.error(msg);
    // data.forEach((item) => (item.key = item._id));
    setcategoryList(data);
  }
  const showModal = (item) => {
    setIsModalVisible(true);
    if (item._id) {
      setIsUpdateCategory(true);
      setTimeout(() => {
        formRef.current.setFieldsValue({
          categoryName: item.name,
        });
      }, 0);
    }
    console.log({ item });
  };
  const handleOk = async () => {
    const res = await form.validateFields().catch((e) => e);
    if (typeof res.errorFields !== "undefined") return;
    const addRes = await addCategoryApi(res.username);
    if (addRes.status === 200) {
      getCategoryList();
      message.success("添加分类成功");
    }
    setIsModalVisible(false);
    onReset();
  };
  const handleCancel = () => {
    setIsModalVisible(false);
    onReset();
  };

  useEffect(() => {
    getCategoryList();
  }, []);

  const columns = [
    {
      title: "分类名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "操作",
      // dataIndex: "age",
      key: "age",
      width: "25%",
      align: "center",
      render: (item) => {
        return (
          <Button
            type="link"
            onClick={() => {
              showModal(item);
            }}
          >
            修改操作
          </Button>
        );
      },
    },
  ];
  return (
    <div className="category">
      <Card
        title="Default size card"
        // extra={<a href="#">More</a>}
        style={{ width: 300 }}
        loading={isLoading}
      >
        <Table
          dataSource={categoryList}
          columns={columns}
          bordered
          rowKey="_id"
          pagination={{ pageSize: 5 }}
        />
        <Button type="primary" onClick={showModal}>
          +添加
        </Button>
      </Card>
      <Modal
        title={`${isUpdateCategory ? "修改" : "新增"}分类`}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Button htmlType="button" onClick={onReset}>
          Reset
        </Button>
        <Form name="editCategory" form={form} ref={formRef}>
          <Form.Item
            name="categoryName"
            initialValue={""}
            rules={[
              {
                required: true,
                message: "不能为空",
              },
            ]}
          >
            <Input placeholder="....." />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default Category;
